// pages/mch/car/add.js
const App = getApp()
import Util from '../../../utils/util'
import Qiniu from '../../../utils/qiniu'
import Kits from '../../../utils/kits'

// 节流函数
function throttle(fn, delay) {
  let last = 0;
  return function (...args) {
    const now = Date.now();
    if (now - last > delay) {
      last = now;
      fn.apply(this, args);
    }
  };
}
// 防抖函数
function debounce(fn, delay) {
  let timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

Page({
  data: {
    init: false,
    loading: false,

    mer: {},
    conf: {},

    top: App.Global.StatusBar + App.Global.CustomBar,

    steps: ["上传行车证", "车辆信息", "价格/分润", "增值服务"],
    step: 1,

    activeNames: ['1'],

    colors: [],

    vlca: '',
    photo: '',
    photos: [],
    sid: '',
    name: '',
    cno: '',
    vin: '',
    eno: '',
    attr_fuel: '',
    attr_color: '',
    attr_year: new Date().getFullYear(),
    attr_liter: '0',
    attr_seat: 0,
    attr_door: 0,
    attr_gearauto: true,
    price_pdp: 0,
    price_pmp: 0,
    price_mdp: 0,
    price_deposit: 0,
    price_disp: 0,
    settle_type: 1,
    settle_rent_base_amt: 0,
    settle_rent_base_uid: '',
    settle_rent_base_name: '',
    settle_rent_spliter: [],
    settle_rate_spliter: [],
    service_onsite_flag: true,
    service_remote_flag: true,
    service_bins_flag: true,
    service_dins_flag: true,
    service_tins_flag: true,
    service_free_flag: true,
    service_night_flag: true,
    service_waive_flag: true,

    option1: [],
    option2: [],
    optionCarData: [],
    option3: [],
    optionColor: [],
    valueColor: '0',
    value1: '',
    value2: '',
    value3: '0',
    colorDedinde: ['黑色', '白色', '银色', '灰色', '蓝色', '红色'],

    title1: '',
    title2: '',
    title3: '',
    title4: '',
    // StyleNum: '',
    carStyleName: '',
    carLogoName: '',
    showDropdown: false,
    carLogoNum: '',
    isActive: false,
    isActiv: false,
    isActivTime: false,
    isActiveColor: false,
    carSelectList: [],
    showwww: true,
    word: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
      'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'W', 'X', 'Y', 'Z'
    ],



    scrollTop: 0,
    contentHeight: 0,
    barHeight: 0,
    barTop: 0,
    initBarTop: 0,
    isDragging: false,
    startY: '',

    scrollTopT: 0,
    contentHeightT: 0,
    barHeightT: 0,
    barTopT: 0,
    initBarTopT: 0,
    isDraggingT: false,
    startYT: '',

    containerHeight: 560,

    isFalse: true,
    showLSbox: false,
    selectCS: '',
    styleTitle: '车型',
    color_exist: false,
    cover: '',
    styleTitleNum: '',
    rpx2px: 0.5
  },
  onReady() {

    // console.log(this.data.contentHeight, "00000000")
  },
  onScroll(e) {
    console.log(e.detail, "滚动值")
    if (this.data.isDragging) return;
    const {
      scrollTop,
      scrollHeight
    } = e.detail;
    const ratio = scrollTop / scrollHeight;
    this.setData({
      barTop: ratio * this.data.rpx2px * 500
    });
    console.log(this.data.barTop, ratio, "滚动事件")
  },
  // 车系
  onScrollT(e) {
    if (this.data.isDragging) return;
    const {
      scrollTop,
      scrollHeight
    } = e.detail;
    const ratio = scrollTop / scrollHeight;
    this.setData({
      barTopT: ratio * this.data.rpx2px * 500
    });
  },
  // 手指触摸开始
  startDrag(e) {
    this.setData({
      // isDragging: true
      startY: Number(e.touches[0].clientY),
      initBarTop: this.data.barTop,
    });
    console.log(e.touches[0].clientY, this.data.barTop, this.data.startY, "触摸事件开始")
  },
  startDragT(e) {
    this.setData({
      // isDragging: true
      startYT: Number(e.touches[0].clientY ),
      initBarTopT: this.data.barTopT
    });
    console.log(e.touches[0].clientY, this.data.barTopT, this.data.startY, "触摸事件开始")
  },
  // 手指触摸移动
  onDrag: throttle(function (e) {
    const newTop = (e.touches[0].clientY - this.data.startY + this.data.initBarTop);
    // this.data.contentHeight - this.data.barHeight
    const maxTop = 500 * this.data.rpx2px;
    console.log("newTop", newTop, maxTop, e.touches[0].clientY , this.data.startY)

    if(newTop > maxTop) {
      return
    }
    this.setData({
      // barTop: Math.max(0, Math.min(newTop, maxTop)),
      scrollTop: (newTop / maxTop) * this.data.contentHeight,
    });

    console.log(e.touches[0].clientY, this.data.startY, this.data.contentHeight, this.data.barHeight, this.data.barTop, this.data.scrollTop, this.data.contentHeight, "触摸事件移动")
  }, 30), // 30ms 节流
  onDragT: throttle(function(e) {
    const newTop = e.touches[0].clientY - this.data.startYT + this.data.initBarTopT;
    // const maxTop = 500;
    const maxTop = 500 * this.data.rpx2px;
    if(newTop > maxTop) {
      return
    }
    this.setData({
      // barTopT: Math.max(0, Math.min(newTop, maxTop)),
      scrollTopT: (newTop / maxTop) * this.data.contentHeightT,
      initBarTop: this.data.barTop
    });

    console.log(e.touches[0].clientY, this.data.startY, this.data.contentHeight, this.data.barHeight, this.data.barTopT, this.data.scrollTop, this.data.scrollHeight, "触摸事件移动")
  }, 30),
  endDrag() {
    this.setData({
      isDragging: false
    });
  },
  endDragT() {
    this.setData({
      isDraggingT: false
    });
  },

  // handleIndexTap(e) {
  //   const index = e.currentTarget.dataset.index
  //   this.setData({ activeIndex: index })

  //   this.createSelectorQuery()
  //     .selectAll('.van-index-anchor')
  //     .boundingClientRect(rects => {
  //       const target = rects.find(r => r.dataset.index === index)
  //       if (target) {
  //         this.setData({ scrollTop: target.top })
  //       }
  //     }).exec()
  // },
  onSelect(e) {
    this.setData({
      activeIndex: e.detail
    })
  },
  // Unicode模式（优化后的区块划分）
  getByUnicode(char) {
    const code = char.charCodeAt(0)
    const blocks = [
      [0x4E00, 0x4E1F, 'A'],
      [0x4E20, 0x4E39, 'B'],
      [0x4E3A, 0x4E85, 'C'],
      [0x4E86, 0x4EA0, 'D'],
      [0x4EA1, 0x4EFD, 'E'],
      [0x4EFF, 0x4F59, 'F'],
      [0x4F5A, 0x4FBF, 'G'],
      [0x4FC0, 0x4FDF, 'H'],
      [0x4FE0, 0x503E, 'J'],
      [0x503F, 0x50FB, 'K'],
      [0x50FC, 0x513F, 'L'],
      [0x5140, 0x51FF, 'M'],
      [0x5200, 0x52BF, 'N'],
      [0x52C0, 0x5320, 'O'],
      [0x5321, 0x53BF, 'P'],
      [0x53C0, 0x54CE, 'Q'],
      [0x54CF, 0x5530, 'R'],
      [0x5531, 0x56D7, 'S'],
      [0x56D8, 0x57CE, 'T'],
      [0x57CF, 0x58F0, 'W'],
      [0x58F1, 0x5B57, 'X'],
      [0x5B58, 0x5F00, 'Y'],
      [0x5F01, 0x9FA5, 'Z']
    ]

    for (const [min, max, initial] of blocks) {
      if (code >= min && code <= max) return initial
    }
    return 'Z'
  },

  // GBK模式（兼容非常用字）
  getByGBK(char) {
    const gbkMap = [
      [0xB0A1, 0xB0C4, 'A'],
      [0xB0C5, 0xB2C0, 'B'],
      [0xB2C1, 0xB4ED, 'C'],
      [0xB4EE, 0xB6E9, 'D'],
      [0xB6EA, 0xB7A1, 'E'],
      [0xB7A2, 0xB8C0, 'F'],
      [0xB8C1, 0xB9FD, 'G'],
      [0xB9FE, 0xBBF6, 'H'],
      [0xBBF7, 0xBFA5, 'J'],
      [0xBFA6, 0xC0AB, 'K'],
      [0xC0AC, 0xC2E7, 'L'],
      [0xC2E8, 0xC4C2, 'M'],
      [0xC4C3, 0xC5B5, 'N'],
      [0xC5B6, 0xC5BD, 'O'],
      [0xC5BE, 0xC6D9, 'P'],
      [0xC6DA, 0xC8BA, 'Q'],
      [0xC8BB, 0xC8F5, 'R'],
      [0xC8F6, 0xCBF9, 'S'],
      [0xCBFA, 0xCDD9, 'T'],
      [0xCDDA, 0xCEF3, 'W'],
      [0xCEF4, 0xD1B8, 'X'],
      [0xD1B9, 0xD4D0, 'Y'],
      [0xD4D1, 0xD7F9, 'Z']
    ]

    try {
      // 浏览器环境使用TextEncoder
      const bytes = new TextEncoder('gbk').encode(char)
      const code = (bytes[0] << 8) | bytes[1]
      for (const [min, max, initial] of gbkMap) {
        if (code >= min && code <= max) return initial
      }
    } catch (e) {
      console.warn('GBK编码转换失败:', e)
    }
    return 'Z'
  },
  getPinyinInitial(str) {
    if (!str || typeof str !== 'string') return ''

    // 优先处理英文（含全角英文）
    const firstChar = str[0]
    if (/[a-zA-ZＡ-Ｚａ-ｚ]/.test(firstChar)) {
      return firstChar.toUpperCase()
    }

    // 模式1：Unicode范围匹配（覆盖基本汉字区）
    const unicodeResult = this.getByUnicode(firstChar)
    if (unicodeResult !== 'Z') return unicodeResult

    // 模式2：GBK编码转换（兼容非常用字）
    return this.getByGBK(firstChar)
  },
  onLoad() {
    App.doPost({
      uri: '/app/merchant/conf/detail',
      body: {},
      fnSucc: resp => {
        this.setData({
          init: true,
          mer: resp.data,
          conf: resp.data.city,
        })
      },
    })
    const systemInfo = wx.getSystemInfoSync();
    const rpx2px = systemInfo.windowWidth / 750;
    this.setData({
      rpx2px
    })
  },
  doPrve() {
    this.setData({
      step: this.data.step - 1
    })
    console.log(this.data.option2, '2222')
  },

  doNextInfo() {
    if (!this.data.cno || !this.data.vin || !this.data.eno) {
      return
    }
    App.doPost({
      uri: '/comm/tool/vin/data',
      body: {
        vin: this.data.vin,
        eno: this.data.eno
      },
      fnSucc: resp => {
        const op1 = [{
          text: resp.data.brand,
          value: String(resp.data.brandid)
        }]
        const op2 = [{
          text: resp.data.name,
          value: String(resp.data.serie.id),
          prop: []
        }]
        const op3 = [{
          text: resp.data.year,
          value: '0'
        }]
        const opColor = resp.data.serie.colors.length > 0 ?
          resp.data.serie.colors.map((item, index) => ({
            text: item,
            value: String(index),
          })) :
          this.data.colorDedinde.map((item, index) => ({
            text: item,
            value: String(index),
          }))

        this.setData({
          step: 2,
          sid: resp.data.serie.id,
          attr_year: resp.data.year,
          attr_liter: resp.data.liter,
          attr_gearauto: resp.data.gearauto,
          attr_door: resp.data.door,
          attr_seat: resp.data.seat,
          attr_fuel: resp.data.fuel,
          name: resp.data.name,
          option1: op1,
          option2: op2,
          option3: op3,
          optionColor: opColor,
          title1: resp.data.brand,
          title2: resp.data.name,
          title3: resp.data.year,
          title4: opColor[0].text,
          value1: String(resp.data.brandid),
          value2: String(resp.data.serie.id),
          value3: '0',
          carLogoName: resp.data.name.split(" ")[0]
        })
        console.log(this.data.optionColor, this.data.value1, "vlaue11", this.data.carLogoName, "Name")
        const defaultSerieId = resp.data.serie.id
        setTimeout(() => {
          App.doPost({
            uri: "/comm/data/car/series",
            body: {
              pager: {
                size: 117,
                page: 1,
              },
              query: {
                bid: this.data.value1
              }
            },
            fnSucc: resp => {
              setTimeout(() => {
                this.setData({
                  optionCarData: resp.data.items
                })
                if(defaultSerieId){
                  const defaultSeriesItem = resp.data.items.find(item => String(item.id) === String(defaultSerieId))
                  if(defaultSeriesItem){
                    // if (defaultSeriesItem.cover && Array.isArray(defaultSeriesItem.cover) && defaultSeriesItem.cover.length > 0) {
                    //   this.setData({
                    //     color_exist: true
                    //   })
                    // } else {
                    //   this.setData({
                    //     color_exist: false
                    //   })
                    // }
                    this.onChangeCarstyle({
                      currentTarget: {
                        dataset: {
                          texta: {
                            value: String(defaultSeriesItem.id)
                          }
                        }
                      }
                    })
                  }
                }
              }, 200)

            }
          })
        }, 200)

      },
      fnFail: (resp) => {
        if (resp.stat.err == 70) {
          Util.Notify.warn(`VIN码不正确，请填写正确或修改识别VIN码`)
        } else if (resp.stat.err == 71 || resp.stat.err == 72 || resp.stat.err == 73) {
          Util.Notify.warn(`未能成功识别车型，请仔细填写车辆资料`)
          this.setData({
            step: 2
          })
        } else {
          Util.Notify.warn(`[${resp.stat.err}] ${resp.stat.msg}`)
        }
      }
    })
  },

  doNextPrice() {
    if (!this.data.photos.length) {
      Util.Notify.warn(`请上传实车照片`)
      return
    }
    if (!this.data.option2) {
      Util.Notify.warn(`请选择车型名称`)
      return
    }
    if (!this.data.option3) {
      Util.Notify.warn(`请选择车型年款`)
      return
    }
    if (!this.data.optionColor) {
      Util.Notify.warn(`请选择车辆颜色`)
      return
    }
    if (!this.data.attr_door || parseInt(this.data.attr_door) < 2) {
      Util.Notify.warn(`请填写车辆门数`)
      return
    }
    if (!this.data.attr_seat || parseInt(this.data.attr_seat) < 2) {
      Util.Notify.warn(`请填写车辆座位数`)
      return
    }
    console.log(this.data.carLogoName, this.data.carStyleName, "NANANAN")
    this.setData({
      step: 3,
      name: (this.data.carLogoName != '' && this.data.carStyleName != '') ? `${this.data.carLogoName} ${this.data.carStyleName}` : this.data.name,
      attr_color: this.data.optionColor[this.data.valueColor].text,
      attr_year: this.data.option3[this.data.value3].text,
      sid: this.data.value2,
    })
    console.log(this.data.name, "name", this.data.attr_color, "color", this.data.sid, "sid", this.data.attr_year, 'year')
  },
  doNextService() {
    if (parseInt(this.data.price_mdp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`终端价格不得低于同行价格`)
      return
    }
    if (parseInt(this.data.price_pmp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`同行月租价格不得低于日租价格`)
      return
    }
    // parseInt(this.data.price_deposit * 100) <= 2000 * 100 ||
    if (parseInt(this.data.price_deposit * 100) <= 2000 * 100 || this.data.price_deposit % 100 !== 0) {
      Util.Notify.warn(`车辆押金不得低于违章押金`)
      return
    }
    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_amt <= 0 || this.data.settle_rent_base_uid == '') {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    if (this.data.settle_type == 3) {
      if (this.data.settle_rate_spliter.length <= 0) {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }

    let k = 1
    let rate_spliter = this.data.settle_rate_spliter.map(spliter => {
      return {
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        sort: k++,
      }
    })
    if (this.data.settle_type == 3) {
      let max = rate_spliter.reduce((p, c) => p + c.rate, 0)
      if (max != 1000) {
        Util.Notify.warn(`请设置正确的租金分配比例`)
        return
      }
    }
    this.setData({
      step: 4
    })
  },

  onChange(event) {
    this.setData({
      activeNames: event.detail,
    });
  },
  doSelectUser() {
    let amt = true
    let rate = true
    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_uid == '') {
        rate = false
      }
    } else {
      amt = false
    }
    wx.navigateTo({
      url: `/pages/mch/car/user?type=${this.data.settle_type}&amt=${amt}&rate=${rate}`,
      events: {
        enter: (seld) => {
          if (this.data.settle_type == 2) {
            if (this.data.settle_rent_base_uid == '') {
              this.setData({
                settle_rent_base_amt: parseFloat(seld.amt),
                settle_rent_base_uid: seld.uid,
                settle_rent_base_name: seld.name,
              })
            } else {
              let spliter = this.data.settle_rent_spliter
              spliter[spliter.length] = {
                uid: seld.uid,
                name: seld.name,
                type: seld.type,
                amt: parseFloat(seld.amt),
                rate: parseFloat(seld.rate),
              }
              let idx = 1
              spliter.forEach(s => {
                s.sort = s.uid == 'share' ? 99999 : idx++
              })
              spliter.sort((m, n) => {
                return m.sort - n.sort
              })

              this.setData({
                settle_rent_spliter: spliter
              })
            }
          } else {
            let spliter = this.data.settle_rate_spliter
            spliter[spliter.length] = {
              uid: seld.uid,
              name: seld.name,
              rate: parseFloat(seld.rate),
            }
            this.setData({
              settle_rate_spliter: spliter
            })
          }

        }
      }
    })
  },
  doDelRentSpliter() {
    let spliter = this.data.settle_rent_spliter
    if (spliter.length > 0) {
      spliter.length = spliter.length - 1
      this.setData({
        settle_rent_spliter: spliter
      })
    } else {
      this.setData({
        settle_rent_base_amt: 0,
        settle_rent_base_uid: '',
        settle_rent_base_name: '',
      })
    }
  },
  doDelRateSpliter() {
    let spliter = this.data.settle_rate_spliter
    if (spliter.length > 0) {
      spliter.length = spliter.length - 1
      this.setData({
        settle_rate_spliter: spliter
      })
    }
  },
  doCertChange(e) {
    let odata = {}
    odata.vlca = e.detail.url
    if (e.detail.ocr.cno) {
      odata["cno"] = e.detail.ocr.cno
      odata["vin"] = e.detail.ocr.vin
      odata["eno"] = e.detail.ocr.eno
      odata["name"] = e.detail.ocr.model
    } else {
      odata["cno"] = ''
      odata["vin"] = ''
      odata["eno"] = ''
      odata["name"] = ''
    }
    this.setData({
      ...odata
    })
  },
  doPictChange(e) {
    let odata = {}
    odata[e.target.dataset.type] = e.detail.url
    this.setData({
      ...odata
    })
  },
  doSettleChange(e) {
    this.setData({
      settle_type: parseInt(e.currentTarget.dataset.type)
    })
  },
  doCheckInput(e) {
    let value = parseFloat(e.detail.value || '0')
    let min = parseFloat(e.target.dataset.min || '0')
    let max = parseFloat(e.target.dataset.max || '99999')
    if (value < min) {
      return min + ''
    }
    if (value > max) {
      return max + ''
    }
    return parseFloat(value.toFixed(2)) + ''
  },
  // 最后保存车辆
  doSaveInfo() {

    if (!this.data.photos.length) {
      Util.Notify.warn(`请上传实车照片`)
      return
    }
    if (!this.data.name) {
      Util.Notify.warn(`请选择车型名称`)
      return
    }
    if (!this.data.cno) {
      Util.Notify.warn(`请填写车牌号码`)
      return
    }
    if (!this.data.vin) {
      Util.Notify.warn(`请填写车架编号`)
      return
    }
    if (!this.data.eno) {
      Util.Notify.warn(`请填写发动机号`)
      return
    }
    if (!this.data.attr_year) {
      Util.Notify.warn(`请选择车型年款`)
      return
    }
    if (!this.data.attr_liter) {
      Util.Notify.warn(`请填写车型排量`)
      return
    }
    if (!this.data.attr_color) {
      Util.Notify.warn(`请选择车辆颜色`)
      return
    }
    if (parseInt(this.data.price_mdp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`终端价格不得低于同行价格`)
      return
    }
    if (parseInt(this.data.price_pmp * 100) <= parseInt(this.data.price_pdp * 100)) {
      Util.Notify.warn(`同行月租价格不得低于日租价格`)
      return
    }
    if (parseInt(this.data.price_deposit * 100) <= 2000 * 100) {
      Util.Notify.warn(`车辆押金不得低于违章押金`)
      return
    }
    if (this.data.settle_type == 2) {
      if (this.data.settle_rent_base_amt <= 0 || this.data.settle_rent_base_uid == '') {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    if (this.data.settle_type == 3) {
      if (this.data.settle_rate_spliter.length <= 0) {
        Util.Notify.warn(`请至少指定一个分润人员`)
        return
      }
    }
    let i = 1
    let rent_spliter = this.data.settle_rent_spliter.map(spliter => {
      return {
        amt: parseInt(spliter.amt * 100),
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        type: spliter.type,
        sort: i++,
      }
    })

    let k = 1
    let rate_spliter = this.data.settle_rate_spliter.map(spliter => {
      return {
        rate: parseInt(spliter.rate * 10),
        uid: spliter.uid,
        sort: k++,
      }
    })
    if (this.data.settle_type == 3) {
      let max = rate_spliter.reduce((p, c) => p + c.rate, 0)
      if (max != 1000) {
        Util.Notify.warn(`请设置正确的租金分配比例`)
        return
      }
    }

    if (this.data.loading) {
      return
    }
    this.setData({
      loading: true
    })
    const params = {
      vlca: this.data.vlca,
      photo: this.data.photos,
      mold: this.data.styleTitleNum,
      color_exist: this.data.color_exist,
      cover: this.data.cover,
      sid: this.data.sid,
      name: this.data.name,
      cno: this.data.cno,
      vin: this.data.vin,
      eno: this.data.eno,
      service: {
        onsite: {
          flag: this.data.service_onsite_flag && this.data.conf.service.onsite.flag && this.data.mer.service.onsite.flag
        },
        remote: {
          flag: this.data.service_remote_flag && this.data.conf.service.remote.flag && this.data.mer.service.remote.flag
        },
        bins: {
          flag: this.data.service_bins_flag && this.data.conf.service.bins.flag && this.data.mer.service.bins.flag
        },
        dins: {
          flag: this.data.service_dins_flag && this.data.conf.service.dins.flag && this.data.mer.service.dins.flag
        },
        tins: {
          flag: this.data.service_tins_flag && this.data.conf.service.tins.flag && this.data.mer.service.tins.flag
        },
        free: {
          flag: this.data.service_free_flag && this.data.conf.service.free.flag && this.data.mer.service.free.flag
        },
        night: {
          flag: this.data.service_night_flag && this.data.conf.service.night.flag && this.data.mer.service.night.flag
        },
        waive: {
          flag: this.data.service_waive_flag && this.data.conf.service.waive.flag && this.data.mer.service.waive.flag
        }
      },
      // -----------------------
      attr: {
        color: this.data.attr_color,
        liter: this.data.attr_liter,
        seat: parseInt(this.data.attr_seat + ''),
        door: parseInt(this.data.attr_door + ''),
        gearauto: this.data.attr_gearauto,
        year: parseInt(this.data.attr_year + ''),
        fuel: this.data.attr_fuel || '未知',
      },
      // -------------------------
      price: {
        pdp: parseInt(this.data.price_pdp * 100),
        pmp: parseInt(this.data.price_pmp * 100),
        mdp: parseInt(this.data.price_mdp * 100),
        deposit: parseInt(this.data.price_deposit * 100),
        disp: parseInt(this.data.price_disp * 100)
      },
      settle: {
        type: this.data.settle_type,
        rent: {
          base: {
            amt: parseInt(this.data.settle_rent_base_amt * 100),
            uid: this.data.settle_rent_base_uid
          },
          spliter: rent_spliter
        },
        rate: {
          spliter: rate_spliter
        }
      }
    }
    console.log('params', params, JSON.stringify(params, null, 2))
    App.doPost({
      uri: '/app/merchant/car/add',
      body: params,
      fnSucc: () => {
        wx.pub("ReloadCarList", {})
        Util.Toast.succ(`提交成功`)
        setTimeout(() => {
          wx.navigateBack({
            delta: 1
          })
        }, 1000);
      },
      fnFail: resp => {
        Util.Notify.error(`[${resp.stat.err}] ${resp.stat.msg}`)
      },
      fnComp: () => {
        this.setData({
          loading: false,
        })
      }
    })

  },
  doUploadImage() {
    if (this.data.photos.length >= 9) {
      Util.Notify.warn(`最多上传9张图片`)
      return
    }
    wx.chooseMedia({
      count: 9 - this.data.photos.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      sizeType: ['compressed'],
      camera: 'back',
      success: (res) => {
        // this.execUpload(res.tempFiles[0].tempFilePath)
        const uploadFun = async () => {
          for (let index = 0; index < res.tempFiles.length; index++) {
            const element = res.tempFiles[index];
            await this.execUpload(element.tempFilePath)
          }
        }
        uploadFun()
      }
    })
  },
  execUpload(path) {
    return new Promise((resolve, reject) => {
      App.doPost({
        uri: '/comm/tool/file/qiniu/info',
        body: {
          type: 'Image'
        },
        fnSucc: resp => {
          let key = resp.data.path + resp.data.fileid + '.' + path.split('.').pop()?.toLowerCase()
          Qiniu.upload(path, (res) => {
            let b64 = ""
            let detail = {
              url: res.imageURL,
              b64: b64,
            }
            console.log('detail', detail)
            this.setData({
              photos: this.data.photos.concat(res.imageURL)
            })
            resolve(null)
          }, (err) => {
            console.log(err)
            resolve(null)
          }, {
            region: 'NCN',
            key: key,
            uptoken: resp.data.token,
            uptokenFunc: null,
            uptokenURL: null,
            domain: resp.data.domain,
            shouldUseQiniuFileName: false,
          }, (progress) => {

          }, (cancel) => {

          })
        },
        fnFail: resp => {
          App.doAlert('出错啦', `上传失败，[${resp.stat.err}] ${resp.stat.msg}`)
          resolve(null)
        }
      })
    })
  },
  doPreviewImage(e) {
    const index = e.currentTarget.dataset.index
    wx.previewImage({
      urls: this.data.photos,
      current: this.data.photos[index]
    })
  },
  doDeleteImage(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      photos: this.data.photos.filter((_, i) => i !== index)
    })
  },
  groupByPinyin(carList) {
    const result = [];
    const pinyinMap = {};

    // 创建拼音字母映射表
    carList.forEach(item => {
      const initial = item.pinyin;
      if (!pinyinMap[initial]) {
        pinyinMap[initial] = [];
      }
      pinyinMap[initial].push({
        text: item.text,
        value: item.value
      });
    });

    // 转换为目标结构
    for (const [code, cars] of Object.entries(pinyinMap)) {
      result.push({
        code: code,
        car: cars
      });
    }

    return result;
  },
  // 车品牌改变时
  onChangeA(e) {
    console.log(e.currentTarget.dataset, "eewe")
    // e.currentTarget.dataset.texta.value   e.detail
    const value = e.currentTarget.dataset.texta.value;
    const selectedOption = this.data.option1.find(item => item.value == value);
    console.log(selectedOption, "selectedOption", value, "vlue", this.data.option1, 'this.data.option1')
    this.setData({
      carLogoName: selectedOption.text,
      carLogoNum: value,
      value1: value,
      title1: selectedOption.text,
      isActive: false,
      showDropdown: false,
      isActiv: false,
      isActivTime: false
    })
    console.log(this.data.carLogoName, "carLogoName")
    // 变车系
    App.doPost({
      uri: "/comm/data/car/series",
      body: {
        pager: {
          size: 117,
          page: 1,
        },
        query: {
          bid: value
        }
      },
      fnSucc: resp => {
        console.log(resp, "车系默认返回")
        const carStyle = []
        // const carYear = []
        resp.data.items.forEach(item => {
          carStyle.push({
            text: item.name,
            value: item.id,
            prop: item.prop
          })
        })
        setTimeout(() => {
          console.log(carStyle, "车系处理后数据")
          this.setData({
            option2: carStyle,
            value2: carStyle[0].value,
            title2: carStyle[0].text,
            carStyleName: carStyle[0].text,
            optionCarData: resp.data.items
          })
        }, 200)
        console.log(this.data.value2, this.data.option2, "vlue222", this.data.carStyleName, "carStyleName")

        // 年款
        // const e = {
        //   detail: this.data.value2
        // }; 
        // 替换为实际需要的value值
        // console.log()
        // this.onChangeCarstyle(e);
      }
    })
  },
  // 车系改变时
  onChangeCarstyle(e) {
    const value = e.currentTarget.dataset.texta.value;
    const selectedOption = this.data.option2.find(item => item.value == value);
    let carYear = []
    let carColor = []
    console.log(selectedOption.text, e.currentTarget.dataset.texta, 'textproblm')
    // this.setData({

    // })
    const targetItem = this.data.optionCarData.find(item => item.id == value)
    const allYear = targetItem.yeargroup.flatMap(item => [item.begin, item.close]);
    const minYea = Math.min(...allYear);
    if (targetItem) {
      carYear = targetItem.yeargroup?.length > 0 ?
        (() => {
          // 提取所有年份并展平
          const allYears = targetItem.yeargroup.flatMap(item => [item.begin, item.close]);
          const minYear = Math.min(...allYears);
          const maxYear = Math.max(...allYears);

          // 生成从 minYear 到 maxYear 的连续年份列表
          return Array.from({
              length: maxYear - minYear + 1
            },
            (_, index) => ({
              text: `${minYear + index}`,
              value: String(index)
            })
          );
        })() :
        Array.from({
          length: 11
        }, (_, index) => ({
          text: `${2016 + index}`,
          value: String(index)
        }));

      // 1. 判断2017所属的年份区间
      const targetYear = minYea
      let matchedRange = null;
      if (targetItem.yeargroup?.length > 0) {
        matchedRange = targetItem.yeargroup.find(
          range => targetYear >= range.begin && targetYear <= range.close
        );
      }

      // 2. 获取匹配的颜色列表
      carColor = (() => {
        // 如果有匹配的年份区间
        if (matchedRange && targetItem.cover) {
          const matchedColors = targetItem.cover
            .filter(item =>
              item.year >= matchedRange.begin &&
              item.year <= matchedRange.close
            )
            // item => item.color
            .map(item => item);
          return matchedColors.length > 0 ?
            matchedColors.map((color, index) => ({
              text: color.color,
              value: String(index),
              url: color.url
            })) :
            this.data.colorDedinde.map((item, index) => ({
              text: item,
              value: String(index),
              url: ''
            }));
        }

        // 默认情况
        return targetItem.cover?.length > 0 ?
          targetItem.cover.map((item, index) => ({
            text: item.color,
            value: String(index),
            url: item.url
          })) :
          this.data.colorDedinde.map((item, index) => ({
            text: item,
            value: String(index),
            url: ''
          }));

      })();

      // 判断颜色图片是否存在
      if (targetItem.cover && Array.isArray(targetItem.cover) && targetItem.cover.length > 0) {
        this.setData({
          color_exist: true
        })
      } else {
        this.setData({
          color_exist: false
        })
      }
    }
    console.log(carYear, carColor, "34324")
    setTimeout(() => {
      this.setData({
        option3: carYear,
        value3: '0',
        title3: carYear[0].text,
        optionColor: carColor,
        title4: carColor[0].text,
        cover: carColor[0].url,
        valueColor: '0',
        // StyleNum: e.detail,
        carStyleName: selectedOption.text,
        // option2: selectedOption,
        value2: value,
        title2: selectedOption.text,
        isActive: false,
        showDropdown: false,
        isActiv: false,
        isActivTime: false,
        showLSbox: false
      })
    }, 200)

  },
  // 年款改变时
  onChangeCarYears(e) {
    this.setData({
      isActivTime: false,
      showDropdown: false,
      isActiv: false,
      isActive: false
    })
    const index = e.currentTarget.dataset.texta.value
    let carColo = []
    const targetItem = this.data.optionCarData.find(item => item.id === this.data.value2)
    console.log(targetItem, "year")
    if (targetItem) {
      // 1. 判断2017所属的年份区间
      const targetYear = Number(this.data.option3[index].text);
      let matchedRange = null;
      if (targetItem.yeargroup?.length > 0) {
        matchedRange = targetItem.yeargroup.find(
          range => targetYear >= range.begin && targetYear <= range.close
        );
      }
      // 2. 获取匹配的颜色列表
      carColo = (() => {
        // 如果有匹配的年份区间
        if (matchedRange && targetItem.cover) {
          const matchedColors = targetItem.cover
            .filter(item =>
              item.year >= matchedRange.begin &&
              item.year <= matchedRange.close
            )
            .map(item => item);
          return matchedColors.length > 0 ?
            matchedColors.map((color, index) => ({
              text: color.color,
              value: String(index),
              url: color.url
            })) :
            this.data.colorDedinde.map((item, index) => ({
              text: item,
              value: String(index),
              url: ''
            }));
        }
        // 默认情况
        return targetItem.cover?.length > 0 ?
          targetItem.cover.map((item, index) => ({
            text: item.color,
            value: String(index),
            url: item.url
          })) :
          this.data.colorDedinde.map((item, index) => ({
            text: item,
            value: String(index),
            url: ''
          }));

      })();
    }
    console.log(carColo, "34324")
    setTimeout(() => {
      this.setData({
        optionColor: carColo,
        value3: String(index),
        title3: this.data.option3[String(index)].text,
        title4: carColo[0].text,
        cover: carColo[0].url
      })
    }, 200)
  },
  // 颜色改变
  colorChange(e) {
    let num = e.currentTarget.dataset.texta.value
    this.setData({
      valueColor: num,
      title4: this.data.optionColor[num].text,
      cover: this.data.optionColor[num].url,
      isActiveColor: false,
      showDropdown: false
    })
    console.log(this.data.cover, "图片地址")
  },
  // 打开车品牌时
  onDropdownOpen() {
    if (this.data.isActive == false) {
      this.setData({
        isActive: true,
        showDropdown: true,
        isActiv: false,
        isActiveColor: false,
        isActivTime: false,
        barTop: 0,
      })
    } else {
      this.setData({
        isActive: false,
        showDropdown: false
      })
    }
    App.doPost({
      uri: "/comm/data/car/brands",
      body: {},
      fnSucc: resp => {
        console.log(resp, "logooo")
        const carName = []
        resp.data.items.forEach(item => {
          carName.push({
            text: item.name,
            value: item.id,
            pinyin: this.getPinyinInitial(item.name)
          })
        })
        // 排序
        // carName.sort((a, b) => a.pinyin.localeCompare(b.pinyin))
        const carSelectList = this.groupByPinyin(carName)


        setTimeout(() => {
          carSelectList.sort((a, b) => a.code.localeCompare(b.code))
          console.log(carName, carSelectList, "cccccc")
          this.setData({
            option1: carName,
            carSelectList: carSelectList,
          })
          const query = wx.createSelectorQuery();
          query.select('#contentBox').boundingClientRect(res => {
            console.log(res, "00000000")
            this.setData({
              contentHeight: res.height,
              barHeight: Math.min(
                100,
                this.data.containerHeight * (this.data.containerHeight / res.height))
            });
            console.log(this.data.contentHeight, this.data.barHeight, "高")
          }).exec();
        }, 200)

      }
    })
  },
  // 打开车系
  onDropdownOpenT() {
    if (this.data.isActiv == false) {
      this.setData({
        isActiv: true,
        isActivTime: false,
        isActive: false,
        isActiveColor: false,
        showDropdown: true,
        isFalse: true,
        showLSbox: false,
        barTopT: 0
      })
    } else {
      this.setData({
        isActiv: false,
        showDropdown: false,
        showLSbox: false
      })
    }
    // if (this.data.carLogoNum == '') {
    App.doPost({
      uri: "/comm/data/car/series",
      body: {
        pager: {
          size: 117,
          page: 1,
        },
        query: {
          bid: this.data.value1
        }
      },
      fnSucc: resp => {
        console.log(resp, "车系默认返回")
        const carStyle = []
        // const carYear = []
        resp.data.items.forEach(item => {
          carStyle.push({
            text: item.name,
            value: item.id,
            prop: item.prop,
            isFalse: true
          })
        })
        setTimeout(() => {
          console.log(carStyle, "车系处理后数据")
          this.setData({
            option2: carStyle,
            optionCarData: resp.data.items,
          })
          const query = wx.createSelectorQuery();
          query.select('#contentBoxT').boundingClientRect(res => {
            console.log(res, "00000000")
            this.setData({
              contentHeightT: res.height,
              barHeightT: Math.min(
                100,
               this.data.containerHeight * ( this.data.containerHeight / res.height))
            });
          }).exec();
        }, 200)
        console.log(this.data.value2, "vlue222")
      }
    })
    // }

  },
  // 打开时间
  onDropdownOpenTh() {
    if (this.data.isActivTime == false) {
      this.setData({
        isActivTime: true,
        isActive: false,
        isActiv: false,
        isActiveColor: false,
        showDropdown: true
      })
    } else {
      this.setData({
        isActivTime: false,
        showDropdown: false
      })
    }
    let carYear = []
    let carColor = []
    console.log(this.data.optionCarData, this.data.value2, "打开年款")
    const targetItem = this.data.optionCarData.find(item => item.id === this.data.value2)
    const allYear = targetItem.yeargroup.flatMap(item => [item.begin, item.close]);
    const minYea = Math.min(...allYear);
    if (targetItem) {
      carYear = targetItem.yeargroup?.length > 0 ?
        (() => {
          // 提取所有年份并展平
          const allYears = targetItem.yeargroup.flatMap(item => [item.begin, item.close]);
          const minYear = Math.min(...allYears);
          const maxYear = Math.max(...allYears);

          // 生成从 minYear 到 maxYear 的连续年份列表
          return Array.from({
              length: maxYear - minYear + 1
            },
            (_, index) => ({
              text: `${minYear + index}`,
              value: String(index)
            })
          );
        })() :
        Array.from({
          length: 11
        }, (_, index) => ({
          text: `${2016 + index}`,
          value: String(index)
        }));

      // 1. 判断2017所属的年份区间
      const targetYear = minYea
      let matchedRange = null;
      if (targetItem.yeargroup?.length > 0) {
        matchedRange = targetItem.yeargroup.find(
          range => targetYear >= range.begin && targetYear <= range.close
        );
      }

      // 2. 获取匹配的颜色列表
      carColor = (() => {
        // 如果有匹配的年份区间
        if (matchedRange && targetItem.cover) {
          const matchedColors = targetItem.cover
            .filter(item =>
              item.year >= matchedRange.begin &&
              item.year <= matchedRange.close
            )
            .map(item => item.color);

          return matchedColors.length > 0 ?
            matchedColors.map((color, index) => ({
              text: color,
              value: String(index),
            })) :
            this.data.colorDedinde.map((item, index) => ({
              text: item,
              value: String(index),
            }));
        }

        // 默认情况
        return targetItem.color?.length > 0 ?
          targetItem.color.map((item, index) => ({
            text: item,
            value: String(index),
          })) :
          this.data.colorDedinde.map((item, index) => ({
            text: item,
            value: String(index),
          }));

      })();

    }

    console.log(carYear, carColor, "34324")
    setTimeout(() => {
      this.setData({
        option3: carYear,
        value3: '0',
        title3: carYear[0].text,
        optionColor: carColor,
        valueColor: '0',
        title4: carColor[0].text
      })
    }, 200)
  },
  // 打开颜色
  openColor() {
    if (this.data.isActiveColor == false) {
      this.setData({
        isActiveColor: true,
        isActivTime: false,
        isActive: false,
        isActiv: false,
        showDropdown: true
      })
    } else {
      this.setData({
        isActiveColor: false,
        showDropdown: false
      })
    }
  },
  // 打开车型
  openStyleC(e) {
    console.log(e.currentTarget.dataset.texta)
    this.setData({
      selectCS: e.currentTarget.dataset.texta.value
    })
    if (this.data.isFalse == true) {
      this.setData({
        isFalse: false,
        showLSbox: true
      })
    } else {
      this.setData({
        isFalse: true,
        showLSbox: false
      })
    }
  },
  // 选择车
  sureStyle(e) {
    console.log(e.currentTarget.dataset)
    this.setData({
      styleTitle: e.currentTarget.dataset.surestyle.style,
      styleTitleNum: e.currentTarget.dataset.surestyle.key,
      showLSbox: false,
      isFalse: true
    })
  }
  // 关闭弹窗
  // onClose() {
  //   this.setData({
  //     showDropdown: false
  //   })
  // }
})